/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.devicereservation.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import vip.xiaonuo.biz.modular.devicereservation.enums.DeviceReservationStatusEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.deviceinfo.entity.DeviceInfo;
import vip.xiaonuo.biz.modular.deviceinfo.service.DeviceInfoService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.biz.modular.devicereservation.entity.DeviceReservation;
import vip.xiaonuo.biz.modular.devicereservation.mapper.DeviceReservationMapper;
import vip.xiaonuo.biz.modular.devicereservation.param.*;
import vip.xiaonuo.biz.modular.devicereservation.service.DeviceReservationService;
import vip.xiaonuo.biz.modular.devicereservation.service.DeviceReservationStatusService;
import vip.xiaonuo.dev.api.DevConfigApi;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;



/**
 * 设备预约Service接口实现类
 *
 * @author Blurryface
 * @date  2025/04/27 14:47
 **/
@Slf4j
@Service
public class DeviceReservationServiceImpl extends ServiceImpl<DeviceReservationMapper, DeviceReservation> implements DeviceReservationService {
    public static final String DEVICE_LOCK_PREFIX = "device-lock";
    
    @Resource
    private CommonCacheOperator commonCacheOperator;

    @Resource
    private DevConfigApi devConfigApi;

    @Autowired
    private DeviceInfoService deviceInfoService;
    
    @Resource
    private DeviceReservationStatusService deviceReservationStatusService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Page<DeviceReservation> page(DeviceReservationPageParam deviceReservationPageParam) {
        QueryWrapper<DeviceReservation> queryWrapper = new QueryWrapper<DeviceReservation>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(deviceReservationPageParam.getTypeId())) {
            queryWrapper.lambda().like(DeviceReservation::getTypeId, deviceReservationPageParam.getTypeId());
        }
        if(ObjectUtil.isNotEmpty(deviceReservationPageParam.getDeviceName())) {
            queryWrapper.lambda().like(DeviceReservation::getDeviceName, deviceReservationPageParam.getDeviceName());
        }
        if(ObjectUtil.isNotEmpty(deviceReservationPageParam.getUserName())) {
            queryWrapper.lambda().like(DeviceReservation::getUserName, deviceReservationPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(deviceReservationPageParam.getStartReservationDate()) && ObjectUtil.isNotEmpty(deviceReservationPageParam.getEndReservationDate())) {
            queryWrapper.lambda().between(DeviceReservation::getReservationDate, deviceReservationPageParam.getStartReservationDate(), deviceReservationPageParam.getEndReservationDate());
        }
        if(ObjectUtil.isNotEmpty(deviceReservationPageParam.getTimeSlot())) {
            queryWrapper.lambda().like(DeviceReservation::getTimeSlot, deviceReservationPageParam.getTimeSlot());
        }
        if(ObjectUtil.isAllNotEmpty(deviceReservationPageParam.getSortField(), deviceReservationPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(deviceReservationPageParam.getSortOrder());
            queryWrapper.orderBy(true, deviceReservationPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(deviceReservationPageParam.getSortField()));
        }
        if (ObjectUtil.isNotEmpty(deviceReservationPageParam.getStatus())){
            queryWrapper.lambda().eq(DeviceReservation::getStatus, deviceReservationPageParam.getStatus());
        }
        else {
            queryWrapper.lambda().orderByDesc(DeviceReservation::getCreateTime);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(DeviceReservationAddParam deviceReservationAddParam) {
        DeviceReservation deviceReservation = BeanUtil.toBean(deviceReservationAddParam, DeviceReservation.class);
        // redis加锁
        String deviceLock = getDeviceLock(deviceReservationAddParam.getReservationDate(),
                deviceReservationAddParam.getTimeSlot(),
                deviceReservationAddParam.getDeviceId());
        if(deviceLock == null) {
            throw new CommonException("设备已被预约，设备ID为：{}", deviceReservationAddParam.getDeviceId());
        }
        try {
            //回查数据库是否被预约
            if (!isDeviceAlreadyReserved(deviceReservationAddParam.getReservationDate(),
                    deviceReservationAddParam.getTimeSlot(),
                    deviceReservationAddParam.getDeviceId())
            ) {
                throw new CommonException("Oops！设备刚刚已被其他用户预约，预约日期：{}，预约时间段：{}，设备ID：{}，请重新选择设备",
                        deviceReservationAddParam.getReservationDate(),
                        deviceReservationAddParam.getTimeSlot(),
                        deviceReservationAddParam.getDeviceId());
            }
            // 回填 设备ID 和 用户ID
            DeviceReservationAddUserDeviceID(deviceReservationAddParam, deviceReservation);
            // 自动审核
            DeviceReservation finalDeviceReservation = checkAutoApproval(deviceReservation);

            this.save(finalDeviceReservation);
            
            // 自动过期并修改预约状态
            if ("已批准".equals(finalDeviceReservation.getStatus())) {
                deviceReservationStatusService.setReservationEndTime(finalDeviceReservation);
            }
        } finally {
            commonCacheOperator.remove(deviceLock);
        }
    }

    /**
     * 获取设备的锁
     */
    private String getDeviceLock(String reservationDate, String timeSlot, String deviceId) {
        String lockKey = DEVICE_LOCK_PREFIX + '_' + reservationDate + '_' + timeSlot + '_' + deviceId;
        if(commonCacheOperator.get(lockKey) != null) {
            return null;
        }
        commonCacheOperator.put(lockKey, "LOCKED", 300);
        return lockKey;
    }

    /**
     * 在数据库中回查设备是否已被预约
     */
    private boolean isDeviceAlreadyReserved(String reservationDate, String timeSlot, String deviceId) {
        //回查数据库是否被预约
        QueryWrapper<DeviceReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("RESERVATION_DATE", reservationDate)
                .eq("TIME_SLOT", timeSlot)
                .eq("DEVICE_ID", deviceId)
                .eq("DELETE_FLAG", "NOT_DELETE")
                .ne("STATUS", "已取消");
        return this.count(queryWrapper) <= 0;
    }

    /**
    *   添加设备预约信息时额外保存预约的用户ID和预约的设备ID
    */
    private void DeviceReservationAddUserDeviceID(DeviceReservationAddParam deviceReservationAddParam, DeviceReservation deviceReservation){
        String deviceName = deviceReservationAddParam.getDeviceName();
        //根据设备名查设备ID
        QueryWrapper<DeviceInfo> deviceInfoQueryWrapper = new QueryWrapper<>();
        deviceInfoQueryWrapper.lambda().eq(DeviceInfo::getName, deviceName);
        DeviceInfo deviceInfo = deviceInfoService.getOne(deviceInfoQueryWrapper);
        if(ObjectUtil.isNull(deviceInfo)) {
            throw new CommonException("设备不存在，设备名称为：{}", deviceName);
        }
        //保存设备ID和前端传入的一些参数
        deviceReservation.setDeviceId(deviceInfo.getId());
        //获取当前B端登录用户的ID
        String loginIdAsString = StpUtil.getLoginIdAsString();
        deviceReservation.setUserId(loginIdAsString);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(DeviceReservationEditParam deviceReservationEditParam) {
        DeviceReservation deviceReservation = this.queryEntity(deviceReservationEditParam.getId());
        String oldStatus = deviceReservation.getStatus();
        
        BeanUtil.copyProperties(deviceReservationEditParam, deviceReservation);
        this.updateById(deviceReservation);
        
        // 如果状态从非"已批准"变为"已批准"，则设置预约结束时间
        if (!"已批准".equals(oldStatus) && "已批准".equals(deviceReservation.getStatus())) {
            deviceReservationStatusService.setReservationEndTime(deviceReservation);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<DeviceReservationIdParam> deviceReservationIdParamList) {
        List<String> idList = CollStreamUtil.toList(deviceReservationIdParamList, DeviceReservationIdParam::getId);
        
        // 删除Redis中的过期键
        for (String id : idList) {
            deviceReservationStatusService.removeFromDelayQueue(id);
        }
        
        // 执行删除
        this.removeByIds(idList);
    }

    @Override
    public void cancel(DeviceReservationIdParam deviceReservationIdParam) {
        QueryWrapper<DeviceReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DeviceReservation::getId, deviceReservationIdParam.getId());
        DeviceReservation deviceReservation = this.getOne(queryWrapper);
        if(ObjectUtil.isEmpty(deviceReservation)) {
            throw new CommonException("设备预约不存在，id值为：{}", deviceReservationIdParam.getId());
        }
        if(!Objects.equals(deviceReservation.getStatus(), DeviceReservationStatusEnum.COMPLETED.getValue())) {
            deviceReservation.setStatus(DeviceReservationStatusEnum.CANCELLED.getValue());
            this.updateById(deviceReservation);
        }

        deviceReservationStatusService.removeFromDelayQueue(deviceReservationIdParam.getId());
    }

    @Override
    public DeviceReservation detail(DeviceReservationIdParam deviceReservationIdParam) {
        return this.queryEntity(deviceReservationIdParam.getId());
    }

    @Override
    public DeviceReservation queryEntity(String id) {
        DeviceReservation deviceReservation = this.getById(id);
        if(ObjectUtil.isEmpty(deviceReservation)) {
            throw new CommonException("设备预约不存在，id值为：{}", id);
        }
        return deviceReservation;
    }

    @Override
    public List<String> getReservedDevices(DeviceReservationQueryParam param) {
        // 查询指定设备类型、日期和时间段已被预约的设备ID
        QueryWrapper<DeviceReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("RESERVATION_DATE", param.getReservationDate())
                .eq("TIME_SLOT", param.getTimeSlot())
                .eq("TYPE_ID", param.getTypeId())
                .eq("DELETE_FLAG", "NOT_DELETE")
                .ne("STATUS", "已取消"); // 排除已取消的预约
        
        // 如果是编辑模式，排除当前编辑的记录
        if (ObjectUtil.isNotEmpty(param.getId())) {
            queryWrapper.ne("ID", param.getId());
        }

        List<DeviceReservation> reservations = this.list(queryWrapper);

        List<String> res = new ArrayList<>();
        for (DeviceReservation item : reservations) {
            res.add(item.getDeviceId());
        }

        return res;
    }
    
    /**
     * 检查是否开启自动审核并处理预约信息
     */
    public DeviceReservation checkAutoApproval(DeviceReservation deviceReservation) {
        String autoApprovalFlag = devConfigApi.getValueByKey("BIZ_DEVICE_RESERVATION_AUTO_APPROVAL");
        if (Objects.equals(autoApprovalFlag, "true")) {
            deviceReservation.setStatus("已批准");
            deviceReservation.setApproverName("自动审核");
//            deviceReservation.setApprovalTime();
            deviceReservation.setApprovalRemark("系统自动审核通过");
        } else {
            // 未开启自动审核，设置为待审核状态
            deviceReservation.setStatus("待审核");
        }
        return deviceReservation;
    }
}
